<?php


namespace backend\modules\tool\DataSource\Log;
use backend\modules\tool\DataSource\Task\command\CommandFaced;
use backend\modules\tool\DataSource\Task\command\WindowsCommad;
use backend\modules\tool\helpers\FileHelper;
use backend\modules\tool\helpers\functions;
use function Symfony\Component\String\s;

define("pid_path",dirname(__DIR__)."/Filesystem/pid/");

class PidRecord
{
    protected static $obj=[];
    protected $task_id;
    protected $record_path;

    /**
     * @param $task_id
     * @return PidRecord
     */
    public static function SingleTon($task_id){
        $task_id=str_replace("/","_",$task_id);
        if(empty(self::$obj[$task_id])){
            self::$obj[$task_id]=new self($task_id);
        }
        return self::$obj[$task_id];
    }
    protected function __construct($task_id)
    {
        $this->task_id=$task_id;
        $this->record_path=pid_path."{$task_id}.pid";
        FileHelper::mkdir(pid_path);
    }

    /**
     * 获取当前运行的子进程
     * @return int
     */
    public static function getRunningProcess(){
        $num=0;
        $pids=FileHelper::FileWalk(pid_path);
        foreach ($pids as $pid){
            $real_pid=FileHelper::GetFileName($pid,"");
            if(PidRecord::SingleTon($real_pid)->IsRun()){
                $num+=1;
            }
        }
        return $num;
    }
    public function recordMyPid(){
        var_dump(CommandFaced::getDirver()->getMyPid());
        file_put_contents($this->record_path,CommandFaced::getDirver()->getMyPid());
    }
    /**
     * @return bool
     */
    public function IsRun(){
        if(!is_file($this->record_path)){
            return false;
        }
        $pid=file_get_contents($this->record_path);
        if(!CommandFaced::getDirver()->isRun($pid)){
            try {
                unlink($this->record_path);
            }
            catch (\Exception $exception){

            }
            return false;
        }
        return true;
    }

    /**
     * 结束运行删除pid记录
     */
    public function finish(){
        if(is_file($this->record_path)){
            unlink($this->record_path);
        }
    }
    public function getPid(){
        if(is_file($this->record_path)){
            return file_get_contents($this->record_path);
        }else{
            return -1;
        }
    }

}